package role

import (
	"context"
	"net/http"

	"go-zero-admin/apps/system/cmd/api/internal/svc"
	"go-zero-admin/apps/system/cmd/api/internal/types"
	"go-zero-admin/apps/system/cmd/rpc/syspb"

	"github.com/jinzhu/copier"
	"github.com/zeromicro/go-zero/core/logx"
)

type GetRoleLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
	r      *http.Request
}

func NewGetRoleLogic(ctx context.Context, svcCtx *svc.ServiceContext, r *http.Request) *GetRoleLogic {
	return &GetRoleLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
		r:      r,
	}
}

func (l *GetRoleLogic) GetRole(req *types.GetRoleReq) (resp *types.GetRoleResp, err error) {
	roleResp, err := l.svcCtx.RoleRpc.GetRoleOne(l.ctx, &syspb.GetRoleOneReq{
		Id: req.Id,
	})
	if err != nil {
		return nil, err
	}

	var role types.SysRole
	_ = copier.Copy(&role, roleResp.GetOne())

	// 获取该角色所绑定的菜单id
	menuIdListResp, err := l.svcCtx.RoleRpc.GetRoleRuleByRid(l.ctx, &syspb.GetRoleRuleByRidReq{
		Id: req.Id,
	})
	if err != nil {
		return nil, err
	}
	ruleIds := menuIdListResp.GetRuleIds()
	if len(ruleIds) == 0 {
		ruleIds = []int64{}
	}

	return &types.GetRoleResp{
		Role:    &role,
		MenuIds: ruleIds,
	}, nil
}
